﻿using System;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.ITME.Entities;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.ITME.Activities
{
    [Apiumc("ITME", "Group", Auth = WebAuthType.Admin, Desc = "应用分组")]
    class SiteGroupActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var key = this.AsyncDialog("Key", g => this.DialogValue("SelectGroup"));
            var Roots = this.AsyncDialog("Root", "None");
            var type = Utility.IntParse(this.AsyncDialog("Type", "0"), 0);
            var GroupKeys = this.AsyncDialog("GroupKey", uk =>
            {
                var uTitle = new UITitle("选择分组");
                var ui = UISection.Create(uTitle);
                var roles = DataFactory.Instance().SiteGroup().Where(r => (r.Type ?? 0) == type).OrderBy(r => r.Seq).ToArray();
                switch (key)
                {
                    case "Editer":
                        uTitle.Title = "分组维护";
                        this.Context.Send("Site.Group.Editer", false);
                        uTitle.Right(new UIEventText("新增").Click(new UIClick(request, "Key", "Editer", uk, "0")));
                        break;
                    case "Data":
                        var rdatas = roles.OrderBy(r => r.Seq).ToList();
                        if (type == 0)
                        {

                            rdatas.Insert(0, new Entities.SiteGroup { Key = 0, Caption = "我的应用", Icon = "\uf00a" });
                        }
                        else
                        {
                            rdatas.Insert(0, new Entities.SiteGroup { Key = 0, Caption = "我的设备", Icon = "\uf108" });
                        }
                        response.Redirect(rdatas);
                        break;
                    default:
                        // if (request.IsMaster)
                        // {
                        //     uTitle.Right(new UIEventText("维护").Click(new UIClick(request, "Key", "Editer")));
                        // }
                        break;
                }


                if (roles.Length == 0)
                {
                    if (key == "Editer")
                    {
                        ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有应用分组，请新增").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
            new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 

                    }
                    else
                    {
                        ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有应用分组，请维护").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                                    new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 

                    }
                }
                else
                {
                    var ui2 = ui.NewSection();

                    foreach (var r in roles)
                    {
                        if (String.IsNullOrEmpty(r.Icon))
                        {
                            ui2.AddCell(r.Caption, new UIClick(request, uk, r.Key.ToString()));
                        }
                        else
                        {
                            ui2.AddCell(r.Icon[0], r.Caption, new UIClick(request, uk, r.Key.ToString()));
                        }

                    }
                }
                if (key == "Editer")
                {
                    ui.SendTo(this.Context, $"{request.Model}.{request.Command}");
                }
                else
                {
                    if (roles.Length > 0)
                    {
                        if (type == 0)
                        {

                            ui.AddCell('\uf00a', "我的应用", new UIClick(request, uk, "0"));
                        }
                        else
                        {

                            ui.AddCell('\uf108', "我的设备", new UIClick(request, uk, "0"));
                        }

                    }
                    ui.SendTo("UI.Event,Site.Group.Editer", this.Context);
                }


            });//, 0);
            var Rolename = Utility.IntParse(GroupKeys, 0);
            switch (key)
            {
                case "Transfer":
                    {
                        if (string.Equals(Roots, "None") == false)
                        {
                            var roots = Roots.Split(',');

                            if (type == 1)
                            {
                                foreach (var rook in roots)
                                {
                                    var device = UMC.Data.HotCache.Get(new Entities.Device { Id = Utility.UInt64Parse(rook, 0) });
                                    if (device != null)
                                    {
                                        UMC.Data.HotCache.Put(new Entities.Device { Id = device.Id, GroupKey = Rolename });
                                    }
                                }

                            }
                            else
                            {
                                foreach (var rook in roots)
                                {
                                    var t = DataFactory.Instance().Site(rook);
                                    if (t != null)
                                    {
                                        DataFactory.Instance().Put(new Site { Root = t.Root, GroupKey = Rolename });
                                    }
                                }
                            }
                        }
                        this.Context.Send($"Site.Group.Editer", true);
                    }
                    break;
                case "SortGroup":
                    {
                        if (string.Equals(Roots, "None") == false && Rolename == 0)
                        {
                            var roots = Roots.Split(',');
                            int start = 1;
                            foreach (var rook in roots)
                            {

                                start++;
                                var gKey = Utility.IntParse(rook, 0);
                                if (gKey != 0)
                                {
                                    if (DataFactory.Instance().SiteGroup(gKey) != null)
                                    {

                                        DataFactory.Instance().Put(new SiteGroup { Key = gKey, Seq = start });
                                    }
                                }
                            }
                            return;
                        }
                    }
                    break;
                case "Sort":
                    {
                        if (string.Equals(Roots, "None") == false)
                        {
                            var roots = Roots.Split(',');

                            var role2 = DataFactory.Instance().SiteGroup(Rolename) ?? new Entities.SiteGroup();
                            int start = (role2?.Seq ?? 0) * 1000;
                            foreach (var rook in roots)
                            {
                                start++;
                                var t = DataFactory.Instance().Site(rook);
                                if (t != null)
                                {
                                    DataFactory.Instance().Put(new Site { Root = t.Root, Seq = start });
                                }
                            }
                            return;
                        }
                    }
                    break;
                case "Editer":

                    if (request.IsMaster == false)
                    {
                        this.Prompt("需要管理员权限才能设置");
                    }
                    var role = DataFactory.Instance().SiteGroup(Rolename) ?? new Entities.SiteGroup();
                    var setting = this.AsyncDialog("Setting", d =>
                    {
                        var frm = new UIFormDialog();
                        frm.Title = "应用分组";
                        if (role.Key.HasValue == false)
                        {
                            frm.Title = "新建分组";
                            frm.AddText("分组名称", "Caption", role.Caption);
                            frm.AddOption("分组图标", "Icon", role.Icon, String.IsNullOrEmpty(role.Icon) ? "请选择" : "已选择")
                            .Command("System", "Icon");

                        }
                        else
                        {

                            frm.AddText("分组名称", "Caption", role.Caption);
                            frm.AddOption("分组图标", "Icon", role.Icon, String.IsNullOrEmpty(role.Icon) ? "请选择" : "已选择")
                            .Command("System", "Icon");

                            frm.AddCheckBox("", "Status", "N").Add("删除此分组", "Del");


                        }

                        return frm;
                    });
                    if ((setting["Status"] ?? String.Empty).Contains("Del"))
                    {
                        if (type == 0)
                        {
                            if (HotCache.Search<Site>().And().Equal(new Site { GroupKey = Rolename }).Query(new Site(), 0, 10, out var _).Length > 0)
                            {
                                this.Prompt("此分组存在关联应用");
                            }
                            HotCache.Delete(new SiteGroup { Key = Rolename });
                        }
                        else
                        {
                            if (HotCache.Search<Device>().And().Equal(new Device { GroupKey = Rolename }).Query(new Device(), 0, 10, out var _).Length > 0)
                            {
                                this.Prompt("此分组存在关联设备");
                            }
                            HotCache.Delete(new SiteGroup { Key = Rolename });
                        }
                    }
                    else
                    {
                        UMC.Data.Reflection.SetProperty(role, setting.GetDictionary());
                        if (role.Key.HasValue == false)
                        {
                            role.Key = Utility.TimeID();
                            role.Seq = role.Key;
                            role.Type = type;
                        }
                        DataFactory.Instance().Put(role);
                    }
                    this.Context.Send($"{request.Model}.{request.Command}", true);
                    break;
            }
            if (Rolename == 0)
            {
                this.Context.UIEvent(key, new ListItem(type == 0 ? "我的应用" : "我的设备", "0"), true);
            }
            else
            {
                var role3 = DataFactory.Instance().SiteGroup(Rolename);

                this.Context.UIEvent(key, new ListItem(role3.Caption, role3.Key.ToString()), true);

            }



        }
    }
}